import React from 'react';
import { connect } from 'umi';
import { Modal, Select, InputNumber } from 'antd';
import { configModal, warnSmall } from '@/assets';
import { NumberSub } from '@/utils';
import {
  PowerStrategyType,
  PriceStrategyType,
  PriceType,
} from '@/pages/Tianji/DayRollingTradeStrategy/constant.js';
import styles from './index.less';

const { Option } = Select;

function PriceSettingModal(
  { hourOrderList, strategyPowerType, upperPrice, lowerPrice, dispatch },
  ref,
) {
  React.useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = React.useState(false),
    [strategyType, setStrategyType] = React.useState(PriceStrategyType.FLOAT),
    [fixedPrice, setFixedPrice] = React.useState(0),
    [buyType, setBuyType] = React.useState(PriceType.DOWN),
    [buyPrice, setBuyPrice] = React.useState(0),
    [sellType, setSellType] = React.useState(PriceType.UP),
    [sellPrice, setSellPrice] = React.useState(0);

  const initHandle = () => {
    setFixedPrice(upperPrice);
    setShowModal(true);
  };

  const confirm = () => {
    // 计算24个时点的电价数据
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    hourOrderListNew.forEach((item) => {
      // 获取交易量
      let tradePower =
        strategyPowerType === PowerStrategyType.TARGET_POSITION
          ? item.strategyPower - item.holdings
          : item.strategyPower;

      let strategyPrice;
      if (strategyType === PriceStrategyType.FIXED) {
        // 固定价格
        strategyPrice = fixedPrice;
      } else {
        if (tradePower >= 0) {
          // 卖出
          switch (sellType) {
            case PriceType.UP:
              strategyPrice = parseFloat((item.upperPrice - sellPrice).toFixed(2));
              break;
            case PriceType.DOWN:
              strategyPrice = parseFloat((item.lowerPrice + sellPrice).toFixed(2));
              break;
            case PriceType.FORECAST:
              strategyPrice = parseFloat((item.forecastPrice + sellPrice).toFixed(2));
              break;
          }
        } else {
          // 买入
          switch (buyType) {
            case PriceType.UP:
              strategyPrice = parseFloat((item.upperPrice - buyPrice).toFixed(2));
              break;
            case PriceType.DOWN:
              strategyPrice = parseFloat((item.lowerPrice + buyPrice).toFixed(2));
              break;
            case PriceType.FORECAST:
              strategyPrice = parseFloat((item.forecastPrice - buyPrice).toFixed(2));
              break;
          }
        }
      }
      if (strategyPrice > item.upperPrice) {
        strategyPrice = item.upperPrice;
      } else if (strategyPrice < item.lowerPrice) {
        strategyPrice = item.lowerPrice;
      }
      item.strategyPrice = strategyPrice;
      item.strategyPowerComputed = false;
      item.strategyPriceComputed = false;
      item.strategyBenefitsComputed = false;
    });
    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });

    setShowModal(false);
  };

  return (
    <Modal
      className={styles.priceSettingModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={configModal} />
          <span className={styles.text}>策略价格设置</span>
        </div>
      }
      visible={showModal}
      okText="确定"
      onCancel={() => {
        setShowModal(false);
      }}
      onOk={confirm}
    >
      <div className={styles.priceStrategyType}>
        <span className={styles.label}>设置方式</span>
        <Select
          className={styles.select}
          value={strategyType}
          onChange={(value) => {
            setStrategyType(value);
          }}
        >
          <Option value={PriceStrategyType.FIXED} key={PriceStrategyType.FIXED}>
            固定价格
          </Option>
          <Option value={PriceStrategyType.FLOAT} key={PriceStrategyType.FLOAT}>
            浮动价格
          </Option>
        </Select>
      </div>
      {strategyType === PriceStrategyType.FIXED ? (
        <div className={styles.fixed}>
          <span className={styles.label}>{''}</span>
          <InputNumber
            className={styles.input}
            precision={2}
            value={fixedPrice}
            onBlur={(e) => {
              let value = e.target.value;
              if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
              let max = upperPrice;
              let min = lowerPrice;
              if (value > max) {
                value = max;
              } else if (value < min) {
                value = min;
              }
              value = NumberSub(value, 2);
              setFixedPrice(value);
            }}
          />
          <span>元/MWh</span>
        </div>
      ) : (
        <>
          <div className={styles.float}>
            <span className={styles.label}>买入</span>
            <div className={styles.config}>
              <Select
                className={styles.select}
                value={buyType}
                onChange={(value) => {
                  setBuyType(value);
                }}
              >
                <Option value={PriceType.UP} key={PriceType.UP}>
                  上限价
                </Option>
                <Option value={PriceType.DOWN} key={PriceType.DOWN}>
                  下限价
                </Option>
                <Option value={PriceType.FORECAST} key={PriceType.FORECAST}>
                  现货价格
                </Option>
              </Select>
              <span>{buyType === PriceType.UP || buyType === PriceType.FORECAST ? '-' : '+'}</span>
              <div className={styles.inputWrap}>
                <InputNumber
                  className={styles.input}
                  precision={2}
                  value={buyPrice}
                  onBlur={(e) => {
                    let value = e.target.value;
                    if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                    // 如果为现货价格，加减值不做处理
                    if (buyType !== PriceType.FORECAST) {
                      let max = upperPrice - lowerPrice;
                      let min = 0;
                      if (value > max) {
                        value = max;
                      } else if (value < min) {
                        value = min;
                      }
                    }

                    value = NumberSub(value, 2);
                    setBuyPrice(value);
                  }}
                />
                <span>元/MWh</span>
              </div>
            </div>
          </div>
          <div className={styles.float}>
            <span className={styles.label}>卖出</span>
            <div className={styles.config}>
              <Select
                className={styles.select}
                value={sellType}
                onChange={(value) => {
                  setSellType(value);
                }}
              >
                <Option value={PriceType.UP} key={PriceType.UP}>
                  上限价
                </Option>
                <Option value={PriceType.DOWN} key={PriceType.DOWN}>
                  下限价
                </Option>
                <Option value={PriceType.FORECAST} key={PriceType.FORECAST}>
                  现货价格
                </Option>
              </Select>
              <span>{sellType === PriceType.UP ? '-' : '+'}</span>
              <div className={styles.inputWrap}>
                <InputNumber
                  className={styles.input}
                  precision={2}
                  value={sellPrice}
                  onBlur={(e) => {
                    let value = e.target.value;
                    if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                    // 如果为现货价格，加减值不做处理
                    if (buyType !== PriceType.FORECAST) {
                      let max = upperPrice - lowerPrice;
                      let min = 0;
                      if (value > max) {
                        value = max;
                      } else if (value < min) {
                        value = min;
                      }
                    }
                    value = NumberSub(value, 2);
                    setSellPrice(value);
                  }}
                />
                <span>元/MWh</span>
              </div>
            </div>
          </div>
        </>
      )}
      <div className={styles.tipMessage}>
        <img className={styles.icon} src={warnSmall} />
        <span className={styles.text}>
          依据山西交易中心日滚动交易序列规则，上限价为{upperPrice}元/MWh，下限价为{lowerPrice}元/MWh
        </span>
      </div>
    </Modal>
  );
}

export default connect(
  ({ dayRollingTradeStragety }) => ({
    hourOrderList: dayRollingTradeStragety.hourOrderList,
    strategyPowerType: dayRollingTradeStragety.strategyPowerType,
    upperPrice: dayRollingTradeStragety.upperPrice,
    lowerPrice: dayRollingTradeStragety.lowerPrice,
  }),
  null,
  null,
  { forwardRef: true },
)(React.forwardRef(PriceSettingModal));
